package com.example.common.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * 通过实现MetaObjectHandler 接口重写其中的插入填充和修改填充的方法
 */
@Component
@Slf4j
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Value("${entity.createTime}")
    private String createTimeName;
    @Value("${entity.updateTime}")
    private String updateTimeName;




    @Override
    public void insertFill(MetaObject metaObject) {

        //判断当前对象的自动填充属性是否包含当前属性
        if (metaObject.hasSetter(createTimeName)){
            log.info("插入数据进行时间填充数据------");
            //实现填充业务逻辑
            this.strictInsertFill(metaObject,createTimeName, LocalDateTime.class,LocalDateTime.now());
            this.strictInsertFill(metaObject,updateTimeName, LocalDateTime.class,LocalDateTime.now());
        }

//        //如果业务层自己赋值就不需要执行自动填充
//        Object age = this.getFieldValByName("age", metaObject);
//        if(age == null){
//            log.info("插入数据进行年龄填充数据------");
//            this.strictInsertFill(metaObject,"age", Integer.class,18);
//        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {

        if (metaObject.hasSetter(updateTimeName)) {
            log.info("修改数据进行时间填充数据------");
            //实现填充业务逻辑
            this.strictUpdateFill(metaObject, updateTimeName, LocalDateTime.class, LocalDateTime.now());
        }
    }
}
